<template>
  <a-config-provider :locale="locale">
    <div id="app">
      <keep-alive v-if="isLogin">
        <router-view v-if="$route.meta.keepAlive" />
      </keep-alive>
      <router-view v-if="!$route.meta.keepAlive || !isLogin" />
    </div>
  </a-config-provider>
</template>

<script>
import { domTitle, setDocumentTitle } from '@/utils/domUtil'
import { i18nRender } from '@/locales'
import { getUnread } from '@/api/system/message'
import { ACCESS_TOKEN, APP_TIME } from '@/store/mutation-types'
import store from '@/store'
import storage from 'store'
import { userRecentlyPro, infoPm } from '@api/login'
import { getProjectList } from '@/api/overview/contract'

export default {
  data() {
    return {
      time: null,
      isLogin: false
    }
  },
  computed: {
    locale() {
      // 只是为了切换语言时，更新标题
      const { title } = this.$route.meta
      title && setDocumentTitle(`${i18nRender(title)} - ${domTitle}`)

      return this.$i18n.getLocaleMessage(this.$store.getters.lang).antLocale
    }
  },
  mounted() {
    this.$globalVue.$on('unReadMsgListener', this.unReadMsgListener)
    window.addEventListener('click', this.handleKeyup)
    let cacheToken = storage.get(ACCESS_TOKEN)
    document.addEventListener('visibilitychange', () => {
      if (document.visibilityState === 'hidden') {
        // console.log('标签页失去焦点')
        cacheToken = storage.get(ACCESS_TOKEN)
      } else {
        const currentToken = storage.get(ACCESS_TOKEN)
        if (cacheToken !== currentToken) {
          cacheToken = currentToken
          this.replacePage()
        }
      }
    })
    this.getSysVersion()
  },
  destroyed() {
    this.$globalVue.$off('unReadMsgListener')
    window.removeEventListener('click', this.handleKeyup)
    this.logout()
  },
  watch: {
    $route(to, from) {
      this.isLogin = !!localStorage.getItem(ACCESS_TOKEN)
      const info = store.getters.userInfo
      // if (this.isLogin && info && info.id && info.isAdmin === 0 && !info.idCard) {
      //   // 如果没有身份证 强制跳转到 用户信息完善页
      //   this.$router.push({ path: '/person' })
      // } else
      if (this.isLogin && info && info.id && info.isRestPwd === 0) {
        // 强制跳转到 修改密码页面
        this.$router.push({ path: '/person', query: { type: 1 } })
      }
    }
  },
  created() {
    // 在页面加载时读取sessionStorage里的状态信息
    if (sessionStorage.getItem('store')) {
      this.$store.replaceState(
        Object.assign(
          {},
          this.$store.state,
          JSON.parse(sessionStorage.getItem('store'))
        )
      )
    }
 
    // 在页面刷新时将vuex里的信息保存到sessionStorage里
    // beforeunload事件在页面刷新时先触发
    window.addEventListener('beforeunload', () => {
      sessionStorage.setItem('store', JSON.stringify(this.$store.state))
    })
  },

  methods: {
    async replacePage () {
      const currentToken = storage.get(ACCESS_TOKEN)
      if (!currentToken) return this.$router.push({ name: 'login' })
      this.$message.warning('检测到页面信息变更，即将为您刷新页面')
      const info = await userRecentlyPro({})
      const isPm = await infoPm()
      const list = await getProjectList({
        pageNumber: 1,
        pageSize: 10000
      })
      const record = info.proInfo || list.page.content[0]
      if (['SYS_ADMIN', 'PROJECT_ADMIN', 'SYS_FINANCE', 'SYS_BIZ'].includes(info.roleCode)) {
        this.$router.push({ path: '/overview/all' })
      } else {
        if (record) {
          if (isPm) {
            this.$router.push({ path: '/site' })
          } else {
            this.$router.push({ path: '/high' })
          }
        } else {
          this.$router.push({ path: '/overview/all' })
        }
      }
      setTimeout(() => {
        window.location.reload()
      }, 1000)
    },
    handleKeyup (event) {
      storage.set(APP_TIME, Date.now(), 30 * 1000)
    },
    unReadMsgListener() {
      if (localStorage.getItem(ACCESS_TOKEN)) {
        getUnread({ proId: localStorage.getItem('CURRENT_PROID') }).then(
          res => {
            this.$globalVue.$emit('unReadMsgCount', res)
          }
        )
      }
      const time = storage.get(APP_TIME)
      if (time) {
        const diff = Date.now() - time
        if (diff > 30 * 60 * 1000) {
          // 超过时间 退出
          this.$store.dispatch('Logout').then(() => {
            this.$router.push({ name: 'login' })
          })
        }
      }
    },
    logout() {
      if (this.time) {
        clearInterval(this.time)
        this.time = null
      }
    },
    getSysVersion() {
      store.dispatch('getSysVersion')
    }
  }
}
</script>

<style>
.link-btn {
  padding: 0;
}
</style>
